package com.lxs.mall.mallseckill.sevice.impl;

import com.alibaba.fastjson.JSON;
import com.lxs.common.constant.OrderConstant;
import com.lxs.common.constant.SeckillConstant;
import com.lxs.common.utils.R;
import com.lxs.common.vo.MemberVO;
import com.lxs.mall.mallseckill.dto.SeckillSkuRedisDto;
import com.lxs.mall.mallseckill.feign.CouponFeignService;
import com.lxs.mall.mallseckill.feign.ProductFeignService;
import com.lxs.mall.mallseckill.interceptor.AuthInterceptor;
import com.lxs.mall.mallseckill.sevice.SeckillService;
import com.lxs.mall.mallseckill.vo.SeckillOrderDTO;
import com.lxs.mall.mallseckill.vo.SeckillSessionEntity;
import com.lxs.mall.mallseckill.vo.SkuInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RFuture;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    /**
     * 查询出当前时间有哪些秒杀活动和商品sku信息
     * @return
     */
    @Override
    public List<SeckillSkuRedisDto> getCurrentSeckillSessionSkus() {
        //1,确定当前时间是属于哪个秒杀活动的
        Long time =new Date().getTime();
        //从redis中查询所有的秒杀活动
        Set<String> keys = redisTemplate.keys(SeckillConstant.SESSION_CHACE_PREFIX + "*");
        for (String key : keys) {
            //seckill:sessions1656468000000_1656469800000
            String replace = key.replace(SeckillConstant.SESSION_CHACE_PREFIX, "");
            //1656468000000_1656469800000
            String[] s = replace.split("_");
            Long startTime=Long.parseLong(s[0]);//活动的开始时间
            Long endTime=Long.parseLong(s[1]);//活动的结束时间
            if(time > startTime&&time < endTime){
                //说明秒杀活动就是当前时间需要参与的活动
                //取出来的是SKU的ID 2_9
                List<String> range= redisTemplate.opsForList().range(key,-100,100);
                BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
                List<String> list= boundHashOps.multiGet(range);
                if(!CollectionUtils.isEmpty(list)){
                    List<SeckillSkuRedisDto> collect = list.stream().map(item -> {
                        SeckillSkuRedisDto dto = JSON.parseObject(item, SeckillSkuRedisDto.class);
                        return dto;
                    }).collect(Collectors.toList());
                    return collect;
                }
            }
        }

        return null;
    }

    @Override
    public void uploadSeckillSku3Days() {
        //1,通过openFeign远程调用coupon系统服务中的接口获取未来3天的秒杀活动的商品
        R r = couponFeignService.getLates3DaysSession();
        if(r.getCode()==0){
            //表示查询操作成功
            String data = (String) r.get("data");
            List<SeckillSessionEntity> seckillSessionEntities = JSON.parseArray(data,SeckillSessionEntity.class);
            //2,上架商品，redis数据保存
            //2.1,缓存每日秒杀的sku基本信息
            saveSessionInfos(seckillSessionEntities);
            //2.2,缓存每日秒杀的商品信息
            saveSessionSkuInfos(seckillSessionEntities);
        }
    }

    @Override
    public SeckillSkuRedisDto getSeckillSessionBySkuId(Long skuId) {
        //1,找到所有参与秒杀的商品的sku信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
        Set<String> keys = hashOps.keys();
        if(!CollectionUtils.isEmpty(keys)){
            String regex="\\d_"+skuId;  //2_1
            for (String key : keys) {
                boolean matches = Pattern.matches(regex, key);
                if(matches){
                    //说明找到了
                    String json = hashOps.get(key);
                    SeckillSkuRedisDto dto = JSON.parseObject(json, SeckillSkuRedisDto.class);
                    return dto;

                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String code, Integer num) {
        //1,根据killI获取当前秒杀商品的信息  Redis中
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
        String json = ops.get(killId);
        if(StringUtils.isNotEmpty(json)){
            //说明商品信息查询成功
            SeckillSkuRedisDto redisDto= JSON.parseObject(json,SeckillSkuRedisDto.class);
            //校验合法性 时效性
            Long startTime=redisDto.getStartTime();
            Long endTime = redisDto.getEndTime();
            Long nowTime= new Date().getTime();
            if(nowTime > startTime&& nowTime < endTime){
                //说明秒杀请求是在商品秒杀活动时间范围内的请求
                //2,校验  随机码和商品是否合法
                String randCode=redisDto.getRandCode();
                Long skuId= redisDto.getSkuId();
                String redisKillId= redisDto.getPromotionSessionId()+"_"+skuId;
                if(randCode.equals(code)&&redisKillId.equals(killId)){
                    //说明随机码合法，秒杀活动Id合法是本次的秒杀活动
                    //3,判断抢购商品数量是否合法
                    if(num<=redisDto.getSeckillLimit().intValue()){
                        //说明满足限购的条件
                        //4,判断是否满足幂等性
                        //只要抢购成功则redis中我们就存储一条信息：userId+sessionId+skuId
                        MemberVO memberVO = (MemberVO) AuthInterceptor.threadLocal.get();
                        Long id= memberVO.getId();
                        String redisKey=id+"_"+redisKillId;
                        Boolean flag = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), (endTime - nowTime), TimeUnit.MILLISECONDS);
                        if(flag){
                            //表示数据插入成功，是第一次操作
                            RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + randCode);
                            try {
                                RFuture<Boolean> booleanRFuture = semaphore.tryAcquireAsync(num, 100, TimeUnit.MILLISECONDS);
                                if(booleanRFuture.isSuccess()){
                                    //表示秒杀成功
                                    //创建订单号
                                    String orderSn = UUID.randomUUID().toString().replaceAll("-","");
                                    //继续完成快速下单操作
                                    SeckillOrderDTO orderDTO=new SeckillOrderDTO();
                                    orderDTO.setMemberId(id);
                                    orderDTO.setNum(num);
                                    orderDTO.setOrderSn(orderSn);
                                    orderDTO.setSecKillPrice(redisDto.getSeckillPrice());
                                    orderDTO.setSkuId(skuId);
                                    //通过RocketMq发送异步创建订单请求消息
                                    rocketMQTemplate.sendOneWay(OrderConstant.ROCKETMQ_SECKILL_ORDER_TOPIC,JSON.toJSONString(orderDTO));
                                    return orderSn;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                }

            }

        }


        return null;
    }

    /**
     * 保存每日的活动信息到redis中
     * @param seckillSessionEntities
     */
    private void saveSessionInfos(List<SeckillSessionEntity> seckillSessionEntities) {
        for (SeckillSessionEntity entity : seckillSessionEntities) {
            //循环每一各存在的活动 key: startTime_endTime
            long startTime =entity.getStartTime().getTime();
            long endTime = entity.getEndTime().getTime();
            //生成key
            String key = SeckillConstant.SESSION_CHACE_PREFIX+startTime+"_"+endTime;
            Boolean flag = redisTemplate.hasKey(key);
            if(!flag){
                //表示这个秒杀活动在redis中不存在，也就是没有上架，需要上架
                //需要存储到redis中的这个活动涉及的相关的商品的skuId
                List<String> collect = entity.getRelationEntities().stream().map(item -> {
                    //秒杀活动存储的value是sessionId_skuId
                    return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,collect);
            }


        }
    }

    /**
     * 存储活动对应的sku信息
     * @param seckillSessionEntities
     */
    private void  saveSessionSkuInfos(List<SeckillSessionEntity> seckillSessionEntities) {

        seckillSessionEntities.stream().forEach(session->{
            //循环取出session，然后取出对应的sku信息，封装相关的信息
            BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
            session.getRelationEntities().stream().forEach(item->{
                        String skuKey=item.getPromotionSessionId()+"_"+item.getSkuId();
                Boolean flag = boundHashOps.hasKey(skuKey);
                if(!flag){
                    SeckillSkuRedisDto redisDto=new SeckillSkuRedisDto();
                    //1,获取sku的基本信息
                    R info = productFeignService.info(item.getSkuId());
                    if(info.getCode()==0){
                        //表示查询成功
                        String  json = (String) info.get("skuInfoJSON");
                        redisDto.setSkuInfoVO(JSON.parseObject(json, SkuInfoVO.class));
                    }
                    BeanUtils.copyProperties(item,redisDto);
                    //3，设置当前商品的秒杀时间
                    redisDto.setStartTime(session.getStartTime().getTime());
                    redisDto.setEndTime(session.getEndTime().getTime());
                    //4. 随机码
                    String token = UUID.randomUUID().toString().replace("-", "");
                    redisDto.setRandCode(token);
                    //绑定对应的活动编号
                    redisDto.setPromotionSessionId(item.getPromotionSessionId());
                    //分布式信号量的处理，限流的目的
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + token);
                    //把秒杀活动的商品数量作为分布式信号量的信号量
                    semaphore.trySetPermits(item.getSeckillCount().intValue());
                    boundHashOps.put(skuKey,JSON.toJSONString(redisDto));

                }

                    }
            );
        });

    }

}
